#include <Arduino.h>
#include <WIFI.h>
#include <WIFIServer.h>
#include <SPI.h>
#include <TFT_eSPI.h>
#include <TJpg_Decoder.h>

// 屏幕图像 -------------------------------------------------------------------------------------------
TFT_eSPI tft = TFT_eSPI();
bool dmaBufferSel = false;
uint16_t dmaBufferPtr[2][10000];
uint8_t recv_buffer[10000];

// WiFi -------------------------------------------------------------------------------------------
const char* ssid = "esp_test";
const char* password = "xcz12345678";
const char* ip = "192.168.22.1";
const short port = 8080;
// tcp对象
WiFiServer server(port);

// 初始化 --------------------------------------------------------------------------------------------
void image_init()
{
    tft.init();
    tft.initDMA();
    tft.setRotation(1);
    tft.fillScreen(TFT_BLACK);
}

void internet_init()
{
    WiFi.mode(WIFI_MODE_AP);
    WiFi.softAP(ssid, password);
    IPAddress ipaddr;
    ipaddr.fromString(ip);
    WiFi.softAPConfig(ipaddr, ipaddr, WiFi.softAPSubnetMask());

    server.begin();
}

bool tft_output(int16_t x, int16_t y, uint16_t w, uint16_t h, uint16_t* bitmap)
{
  if ( y >= tft.height() )
    return 0;
  dmaBufferSel = !dmaBufferSel;
  tft.pushImageDMA(x, y, w, h, bitmap, dmaBufferPtr[dmaBufferSel]);

//   tft.pushImage(x, y, w, h, bitmap);
  return 1;
}
void JpgDecode_init()
{
    TJpgDec.setJpgScale(1);
    TJpgDec.setSwapBytes(true);
    TJpgDec.setCallback(tft_output);
}

void setup()
{
    Serial.begin(9600);

    image_init();
    JpgDecode_init();
    internet_init();
}

// task -------------------------------------------------------------------------------------------
void recv_video(WiFiClient& client)
{
    static int size = 0;
    static int begin = 0;
    size += client.readBytes((uint8_t*)recv_buffer + size, sizeof(recv_buffer) - size);
    if (recv_buffer[size - 5] == 'h' && recv_buffer[size - 4] == 'e' && \
        recv_buffer[size - 3] == 'l' && recv_buffer[size - 2] == 'l' && recv_buffer[size - 1] == 'o')
    {
        int end = millis();
        
        tft.startWrite();
        TJpgDec.drawJpg(0, 0, recv_buffer, size);
        tft.endWrite();
        
        size = 0;
        client.write("ok");
        Serial.println(end - begin);
        begin = end;
    }
}

void loop()
{
    WiFiClient client = server.available();
    if (client)
    {
        client.setTimeout(0);
        while (client.connected())
        {
            if (client.available())
                recv_video(client);
        }
        client.stop();
    }
}
